package com.guohang.ESProject08;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;

public class MainActivity extends Activity {
	
	private static final int CAMERA_REQUEST = 100;
	private Uri fileUri;
	private File image;
	
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    
	//database
	public CommentsDataSource dataSource;
	
	//sensor data
	double temperature = 0;
	double GSR = 0;
	double social = 0;
	double heartRate = 0;
	
	//data
	private List<Capture> story = null;
	
	//image thumbnails
	private ArrayList<File> imgThumb = new ArrayList<File>();
	
	//color picker
	private ColorBarView _blueColorBarView;
    private ColorBarHelper _helper;
    private GridView _layout;
    private int emoColor = 0xffFAFAFA;
    
    //default text
    private String defaultText = "Write something here...";
    
    private final OnColorChangeListener _listener = new OnColorChangeListener() {
        public void onColorChange( final int color ) {
            setColorIndicator( color );
        }
    };
    
    //activity-service communication
	private Handler mHandler = new Handler() {
		    public void handleMessage(Message message) {
		      Bundle data = message.getData();
		      if (message.arg1 == RESULT_OK && data != null) {
		    	  String msg = (String)message.obj;
                 emotionAdapter(msg);;
		      }
		    }
		  };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //initialize database connection
        dataSource = new CommentsDataSource(this);
        dataSource.open();
        
        //image thumbnails
        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this));
    
        //color picker
        assignWidget();
        
        _helper = new ColorBarHelper( new ColorBarView[] {_blueColorBarView } );
        _helper.setOnColorChangeListener(_listener );
        _helper.setRGBColor( emoColor );
        
        setColorIndicator( 0xffabcdef );
        
        //set default text on UI
        EditText editText = (EditText)findViewById(R.id.message);
        editText.setText(defaultText);
        editText.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
			   EditText editText = (EditText)v;
		       String currentText = editText.getText().toString();
			if(currentText.equals(defaultText)){
				editText.setText("");
			}		
			}
		});
        
        //Start Context Service
        Intent mServiceIntent = new Intent(this, ContextService.class);
        
        Messenger messenger = new Messenger(mHandler);
        mServiceIntent.putExtra("MESSENGER", messenger);
        
        //start an empty intent
        this.startService(mServiceIntent);
        
    }

   
    
    private void assignWidget() {
        _blueColorBarView = ( ColorBarView ) findViewById( R.id.blueColorBarView );
        _layout = (GridView)findViewById(R.id.gridview);
    }
    
    private void setColorIndicator( final int color ) {
    	
        _layout.setBackgroundColor(color);
        /*
    	_indicatorTextView.setBackgroundColor( color );
        final int complementary = Color.rgb( 0xff - Color.red( color ) , 0xff - Color.green( color ) , 0xff - Color.blue( color ) );
        _indicatorTextView.setTextColor( complementary );
        _indicatorTextView.setText( String.format( "#%02x%02x%02x" , //
                Color.red( color ) , //
                Color.green( color ) , //
                Color.blue( color ) ) ); 
        */
    }
    
    private void emotionAdapter(String emotion){
    	if(emotion.equals("good")){
    		emoColor = 0xff16BF0A ;
    	} else{
    		emoColor = 0xffF25B10;
    	}
    	
        _helper.setRGBColor( emoColor );
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    public void openCamera(View view){


    	    // create Intent to take a picture and return control to the calling application
    	    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    	    /*
    	    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
    	    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

    	    // start the image capture Intent
    	    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); 	*/
    	    
    	    startActivityForResult(intent, CAMERA_REQUEST);
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
    	
        super.onActivityResult(requestCode, resultCode, data);
        Bitmap scaledphoto = null;
        int height = 200;
        int width = 200;    

        Bitmap photo = (Bitmap) data.getExtras().get("data");
        //resize the photo
        scaledphoto = Bitmap.createScaledBitmap(photo, height, width, true);
        
        //create img storage path
        //fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);         
        image = getOutputMediaFile(MEDIA_TYPE_IMAGE);
        
        //add the new capture to thumbnail display
        imgThumb.add(image);
        
        fileUri = Uri.fromFile(image);
        
        FileOutputStream fos;
        //save image to directory
		try {
			fos = new FileOutputStream(image);
	        scaledphoto.compress(CompressFormat.JPEG, 100, fos);
		    fos.close(); 
			fos.flush();
	}	
	   catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
    }
    
    public void onDone(View view){
    	String imgPath;
    	String message;
    	
    	EditText messageText = (EditText)this.findViewById(R.id.message);
    	
    	//collect data in a capture: img, text
    	if(fileUri != null){
    		imgPath = fileUri.toString();	
    	}else{
    		imgPath = null;
        }
        	message = messageText.getText().toString();

    	    dataSource.insertCapture(message, imgPath, temperature, GSR, heartRate, social);
    	    
    	//clear image path
    	    fileUri = null;
    	//clear thumbnail
    	    imgThumb.clear();
    	    
    }
    
    public void onSend(View view){
    	
    	//step1: read text, image, sensor data from SQLite database
         story = dataSource.getAll();
    	//step2: output information into PDF file.
         CreatePDF PDF = new CreatePDF();
         PDF.PDF(story);
         dataSource.deleteTable();
         
    }
    
    /** Create a file Uri for saving an image or video */
    private static Uri getOutputMediaFileUri(int type){
          return Uri.fromFile(getOutputMediaFile(type));
    }

    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.
    	String external_storage = Environment.getExternalStorageState();
    	
    	File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

        File mediaStorageDir = new File(path, "esUI");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        // Get Timestamp
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "IMG_"+ timeStamp + ".jpg");
        } else if(type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "VID_"+ timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }
    
    //Adapter class for displaying image thumbnail on UI
    public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return imgThumb.size();
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent) {
        	
        	
            ImageView imageView;
            if (convertView == null) {  // if it's not recycled, initialize some attributes
                imageView = new ImageView(mContext); 
                imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8, 8, 8, 8);
            } else {
                imageView = (ImageView) convertView;
            }

            BitmapFactory factory = new BitmapFactory();
            
            String path = imgThumb.get(position).toString();
            if(path != null){
             Bitmap bitMap = factory.decodeFile(path);
             imageView.setImageBitmap(bitMap);
             path = new String();
            //imageView.setImageResource(mThumbIds[position]);
            }
            return imageView;
        }


    }
}
